package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.DoMainUtils;

public class WhnewsNewsAnalyse implements AnalyseNews {

	//http://www.whnews.cn/news/node/2013-05/07/content_5672230.htm
	private static final String[] regex={
		"http://.*.whnews.cn/.*/[0-9]*-[0-9]*/[0-9]*/content_[0-9]*.htm",
	};

	
	public boolean isDetailPage(String url) {
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (urlMeta.getHtml() == null) {
		}
		String url=urlMeta.getUrl();
		if (!isDetailPage(url)) {
		}
//		NewsMeta news=new ParseNewsUtils().parse(urlMeta);
		NewsMeta news=new NewsMeta();
		String htmltxt=urlMeta.getHtml();
		Document doc=Jsoup.parse(htmltxt);
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		title=doc.select("div.news-bt-new").text();
		if (StringUtils.isBlank(title)) {
			title=doc.select("div.sec_l1.heiti.left").text();
		}
		content=HtmlCleaner.getContentHtml(url,doc.select("div.news-main-new"));
		if (StringUtils.isBlank(content)) {
			content=HtmlCleaner.getContentHtml(url,doc.select("div.sec_l5.pt_15"));
		}
		if (StringUtils.isBlank(content)) {
			content=HtmlCleaner.getContentHtml(url,doc.select("#content p"));
		}

		/*
		 * 作者
		 */
		String authorStr=null;
		authorStr=doc.select("div.news-time").text();
		if(StringUtils.isBlank(authorStr)){
			authorStr=doc.select("div.sec_l3_l").text();
		}
		author=StringUtils.substringBetween(authorStr, "来源："," ");
		if(StringUtils.isBlank(author)){
			author=StringUtils.substringAfter(authorStr, "来源：");
		}

		date=DateUtils.matchDate(doc.select("div.news-time").text());
		if (date == null) {
			date=DateUtils.matchDate(doc.select("div.sec_l3_l").text());
		}
		news.setUrl(url);
		news.setTitle(title);
		news.setContent(content);
		news.setAuthor(author);
		news.setDate(date);
		return news;
	}

	public static void main(String[] args) {
		String url="http://www.whnews.cn/news/node/2014-03/28/content_5978411.htm";
		WhnewsNewsAnalyse test=new WhnewsNewsAnalyse();
		url=UrlArgumentTop.FromatUrl(url);
		System.out.println(url);
		System.out.println(DoMainUtils.GetDomainName(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		NewsMeta parserHtml=test.parserHtml(meta);
		System.out.println(parserHtml);
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
}
